<?php
namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\facade\Request;
use think\facade\Log;
use think\facade\Filesystem;

class Jishutuzhi extends BaseController
{
    /**
     * 成功返回
     */
    protected function success($msg = '', $data = null)
    {
        return json([
            'code' => 200,
            'msg' => $msg,
            'data' => $data
        ]);
    }

    /**
     * 失败返回
     */
    protected function error($msg = '', $data = null)
    {
        return json([
            'code' => 400,
            'msg' => $msg,
            'data' => $data
        ]);
    }

    /**
     * 获取图纸分类列表
     */
    public function getCategoryList()
    {
        try {
            // 获取所有分类
            $list = Db::name('drawing_category')
                ->field('id, category_name, parent_id, level')
                ->order('level ASC, id ASC')
                ->select()
                ->toArray();
                
            // 获取每个分类下的图片数量
            $categoryCounts = [];
            foreach ($list as $category) {
                // 获取当前分类及其所有子分类的ID
                $categoryIds = [$category['id']];
                $childrenIds = $this->getAllChildrenIds($category['id']);
                $allIds = array_merge($categoryIds, $childrenIds);
                
                // 统计图片数量
                $count = Db::name('drawing')
                    ->whereIn('category_id', $allIds)
                    ->count();
                    
                $categoryCounts[$category['id']] = $count;
            }
                
            // 构建树形结构
            $tree = $this->buildCategoryTree($list, 0, $categoryCounts);
            
            return $this->success('获取成功', $tree);
        } catch (\Exception $e) {
            Log::error('获取图纸分类列表异常: ' . $e->getMessage());
            return $this->error('获取失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 构建分类树
     */
    private function buildCategoryTree($list, $parentId = 0, $categoryCounts = [])
    {
        $tree = [];
        foreach ($list as $item) {
            if ($item['parent_id'] == $parentId) {
                $children = $this->buildCategoryTree($list, $item['id'], $categoryCounts);
                if (!empty($children)) {
                    $item['children'] = $children;
                }
                $item['label'] = $item['category_name']; // 添加label属性用于前端显示
                $item['count'] = isset($categoryCounts[$item['id']]) ? $categoryCounts[$item['id']] : 0; // 添加图片数量
                $tree[] = $item;
            }
        }
        return $tree;
    }
    
    /**
     * 添加或编辑图纸分类
     */
    public function doEditCategory()
    {
        $data = Request::post();
        
        // 验证必填字段
        if (empty($data['category_name'])) {
            return $this->error('分类名称不能为空');
        }
        
        try {
            $parentId = isset($data['parent_id']) ? intval($data['parent_id']) : 0;
            $level = 1; // 默认为顶级分类
            
            // 如果有父级分类，计算当前分类的层级
            if ($parentId > 0) {
                $parent = Db::name('drawing_category')->where('id', $parentId)->find();
                if (!$parent) {
                    return $this->error('父级分类不存在');
                }
                
                $level = $parent['level'] + 1;
                if ($level > 3) {
                    return $this->error('最多支持三级分类');
                }
            }
            
            $saveData = [
                'category_name' => $data['category_name'],
                'parent_id' => $parentId,
                'level' => $level
            ];
            
            // 新增或更新
            if (isset($data['id']) && $data['id'] > 0) {
                // 检查是否存在循环引用
                if ($data['id'] == $parentId) {
                    return $this->error('不能选择自己作为父级分类');
                }
                
                // 检查是否选择了自己的子分类作为父级分类
                $childrenIds = $this->getAllChildrenIds($data['id']);
                if (in_array($parentId, $childrenIds)) {
                    return $this->error('不能选择子分类作为父级分类');
                }
                
                // 更新
                Db::name('drawing_category')
                    ->where('id', $data['id'])
                    ->update($saveData);
                $msg = '更新成功';
            } else {
                // 新增
                $id = Db::name('drawing_category')->insertGetId($saveData);
                $data['id'] = $id;
                $msg = '添加成功';
            }
            
            return $this->success($msg, $data);
        } catch (\Exception $e) {
            Log::error('添加/编辑图纸分类异常: ' . $e->getMessage());
            return $this->error('操作失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 获取所有子分类ID
     */
    private function getAllChildrenIds($categoryId)
    {
        $ids = [];
        $children = Db::name('drawing_category')->where('parent_id', $categoryId)->column('id');
        $ids = array_merge($ids, $children);
        
        foreach ($children as $childId) {
            $grandChildren = $this->getAllChildrenIds($childId);
            $ids = array_merge($ids, $grandChildren);
        }
        
        return $ids;
    }
    
    /**
     * 删除图纸分类
     */
    public function doDeleteCategory()
    {
        $id = Request::post('id');
        
        if (empty($id)) {
            return $this->error('请选择要删除的分类');
        }
        
        try {
            // 检查是否有子分类
            $hasChildren = Db::name('drawing_category')->where('parent_id', $id)->find();
            if ($hasChildren) {
                return $this->error('该分类下有子分类，不能删除');
            }
            
            // 检查是否有图纸使用该分类
            $hasDrawings = Db::name('drawing')->where('category_id', $id)->find();
            if ($hasDrawings) {
                return $this->error('该分类下有图纸，不能删除');
            }
            
            // 删除分类
            Db::name('drawing_category')->where('id', $id)->delete();
            
            return $this->success('删除成功');
        } catch (\Exception $e) {
            Log::error('删除图纸分类异常: ' . $e->getMessage());
            return $this->error('删除失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 获取图纸列表
     */
    public function getDrawingList()
    {
        $page = input('page/d', 1);
        $pageSize = input('pageSize/d', 20);
        $categoryId = input('category_id/d', 0);
        $keyword = input('keyword/s', '');
        
        try {
            $where = [];
            
            // 按分类筛选
            if ($categoryId > 0) {
                $categoryIds = [$categoryId];
                // 获取所有子分类
                $children = $this->getAllChildrenIds($categoryId);
                $categoryIds = array_merge($categoryIds, $children);
                $where[] = ['category_id', 'in', $categoryIds];
            }
            
            // 按关键词筛选
            if (!empty($keyword)) {
                $where[] = ['drawing_code|technician_name', 'like', "%{$keyword}%"];
            }
            
            // 获取总数
            $count = Db::name('drawing')
                ->where($where)
                ->count();
                
            // 获取列表
            $list = Db::name('drawing')
                ->where($where)
                ->page($page, $pageSize)
                ->order('upload_time DESC')
                ->select()->each(function($item){
                    $item['drawing_url'] = completeUrl($item['drawing_url']);
                    return $item;
                })
                ->toArray();
                
            return $this->success('获取成功', [
                'list' => $list,
                'total' => $count
            ]);
        } catch (\Exception $e) {
            Log::error('获取图纸列表异常: ' . $e->getMessage());
            return $this->error('获取失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 生成图纸编码
     */
    public function generateDrawingCode()
    {
        try {
            $code = $this->generateRandomCode();
            
            // 检查是否已存在
            $exists = Db::name('drawing')->where('drawing_code', $code)->find();
            
            // 如果存在，重新生成直到不重复
            $maxTries = 10;
            $currentTry = 0;
            
            while ($exists && $currentTry < $maxTries) {
                $code = $this->generateRandomCode();
                $exists = Db::name('drawing')->where('drawing_code', $code)->find();
                $currentTry++;
            }
            
            if ($exists) {
                return $this->error('无法生成唯一编码，请稍后再试');
            }
            
            return $this->success('生成成功', ['code' => $code]);
        } catch (\Exception $e) {
            Log::error('生成图纸编码异常: ' . $e->getMessage());
            return $this->error('生成编码失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 生成随机图纸编码：TZ + 年月日时分秒 + 3位随机数
     */
    private function generateRandomCode()
    {
        $prefix = 'TZ';
        $date = date('YmdHis');
        $random = sprintf('%03d', mt_rand(0, 999));
        
        return $prefix . $date . $random;
    }
    
    /**
     * 上传图纸
     */
    public function uploadDrawing()
    {
        // 获取上传文件
        $file = request()->file('file');
        
        if (!$file) {
            return $this->error('请选择要上传的图纸');
        }
        
        // 获取图纸编码（从请求参数中获取）
        $drawingCode = request()->param('drawing_code');
        
        // 如果提供了图纸编码，先检查是否存在
        if (!empty($drawingCode)) {
            $exists = Db::name('drawing')->where('drawing_code', $drawingCode)->find();
            if ($exists) {
                return $this->error('图纸编码已存在，请重新生成');
            }
        }
        
        try {
            // 记录文件信息到日志
            Log::info('上传文件信息: ' . json_encode([
                'name' => $file->getOriginalName(),
                'size' => $file->getSize(),
                'type' => $file->getMime(),
                'ext' => $file->getOriginalExtension()
            ]));
            
            // 检查文件类型
            $fileExt = $file->getOriginalExtension();
            $allowExts = ['jpg', 'jpeg', 'png', 'gif'];
            
            if (!in_array(strtolower($fileExt), $allowExts)) {
                return $this->error('只允许上传jpg、jpeg、png、gif格式的图片');
            }
            
            // 确保上传目录存在
            $uploadPath = public_path() . 'uploads/jishu';
            if (!is_dir($uploadPath)) {
                mkdir($uploadPath, 0755, true);
            }
            
            // 记录上传路径
            Log::info('上传路径: ' . $uploadPath);
            
            // 生成文件名：当前日期时分秒+3位随机数
            $fileName = date('YmdHis') . sprintf('%03d', mt_rand(0, 999)) . '.' . $fileExt;
            $savePath = 'uploads/jishu/' . $fileName;
            
            // 直接移动文件
            $file->move(public_path() . 'uploads/jishu', $fileName);
            
            // 生成URL
            $url = $savePath;
            
            Log::info('文件上传成功: ' . $url);
            
            return $this->success('上传成功', [
                'url' => $url,
                'file_name' => $fileName
            ]);
        } catch (\Exception $e) {
            Log::error('上传图纸异常: ' . $e->getMessage() . "\n" . $e->getTraceAsString());
            return $this->error('上传失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 添加或编辑图纸
     */
    public function doEditDrawing()
    {
        $data = Request::post();
        
        // 验证必填字段
        if (empty($data['drawing_code'])) {
            return $this->error('图纸编码不能为空');
        }
        
        // 如果是只检查编码是否存在
        if (isset($data['check_only']) && $data['check_only']) {
            // 检查编码是否重复
            $exists = Db::name('drawing')
                ->where('drawing_code', $data['drawing_code'])
                ->find();
                
            if ($exists) {
                return $this->error('图纸编码已存在，请重新生成');
            }
            
            return $this->success('图纸编码可用');
        }
        
        if (empty($data['drawing_url'])) {
            return $this->error('图纸URL不能为空');
        }
        if (empty($data['category_id'])) {
            return $this->error('所属分类不能为空');
        }
        
        // 获取当前登录用户信息 - 暂时使用默认值，避免登录验证
        $userId = session('user_id') ?: 1;
        $userName = session('user_name') ?: '管理员';
        
        try {
            $saveData = [
                'drawing_code' => $data['drawing_code'],
                'drawing_url' => $data['drawing_url'],
                'technician_id' => $userId,
                'technician_name' => $userName,
                'category_id' => $data['category_id']
            ];
            
            // 新增或更新
            if (isset($data['id']) && $data['id'] > 0) {
                // 检查编码是否重复
                $exists = Db::name('drawing')
                    ->where('drawing_code', $data['drawing_code'])
                    ->where('id', '<>', $data['id'])
                    ->find();
                    
                if ($exists) {
                    return $this->error('图纸编码已存在');
                }
                
                // 更新
                Db::name('drawing')
                    ->where('id', $data['id'])
                    ->update($saveData);
                $msg = '更新成功';
            } else {
                // 检查编码是否重复
                $exists = Db::name('drawing')
                    ->where('drawing_code', $data['drawing_code'])
                    ->find();
                    
                if ($exists) {
                    return $this->error('图纸编码已存在');
                }
                
                // 添加上传时间
                $saveData['upload_time'] = date('Y-m-d H:i:s');
                
                // 新增
                $id = Db::name('drawing')->insertGetId($saveData);
                $msg = '添加成功';
                $data['id'] = $id;
            }
            
            return $this->success($msg, $data);
        } catch (\Exception $e) {
            Log::error('添加/编辑图纸异常: ' . $e->getMessage());
            return $this->error('操作失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 删除图纸
     */
    public function doDeleteDrawing()
    {
        $ids = Request::post('ids');
        
        if (empty($ids)) {
            return $this->error('请选择要删除的图纸');
        }
        
        try {
            $idArr = explode(',', $ids);
            
            // 只删除图纸记录，保留图纸文件
            Db::name('drawing')->whereIn('id', $idArr)->delete();
            
            return $this->success('删除成功');
        } catch (\Exception $e) {
            Log::error('删除图纸异常: ' . $e->getMessage());
            return $this->error('删除失败: ' . $e->getMessage());
        }
    }
} 